package com.life.xylife.controller;

import java.io.PrintWriter;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.life.util.JsonConfigDate;
import com.life.xylife.service.HttpService;
import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport
{
	
	private String callback;

	public void writeArray(List<?> list)
	{
		HttpService.setRespsonse();
		JSONArray json = JSONArray.fromObject(list);
		PrintWriter writer = null;
		try
		{
			writer = HttpService.getWriter();
			writer.println(json.toString());
			writer.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			if (writer != null)
				writer.close();
		}

	}

	public void writeArrayFtDate(List<?> list)
	{
		JsonConfigDate jsCfg = new JsonConfigDate();
		HttpService.setRespsonse();
		JSONArray json = JSONArray.fromObject(list, jsCfg);
		PrintWriter writer = null;
		try
		{
			writer = HttpService.getWriter();
			writer.println(json.toString());
			writer.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			if (writer != null)
				writer.close();
		}

	}

	public void writeObj(Object o)
	{
		HttpService.setRespsonse();
		PrintWriter writer = null;
		String jsonstr = JSONObject.fromObject(o).toString();
		try
		{
			writer = HttpService.getWriter();
			writer.println(jsonstr);
			writer.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			if (writer != null)
				writer.close();
		}
	}

	public void wirteJsonPStr(String o)
	{
		o = callback + "(" + o + ")";
		writeStr(o);
	}

	public void writeStr(String o)
	{
		HttpService.setRespsonse();
		PrintWriter writer = null;

		try
		{
			writer = HttpService.getWriter();
			writer.println(o);
			writer.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			if (writer != null)
				writer.close();
		}
	}

	public void writeObjDateFt(Object o)
	{
		this.writeStr(this.covtObjectToJson(o));
	}

	public void writeObjDateJsonPFt(Object o)
	{
		this.wirteJsonPStr(this.covtObjectToJson(o));
	}

	public String covtListToJson(Object object)
	{
		JsonConfigDate jsCfg = new JsonConfigDate();
		return JSONArray.fromObject(object, jsCfg).toString();
	}

	public String covtObjectToJson(Object object)
	{
		JsonConfigDate jsCfg = new JsonConfigDate();
		return JSONObject.fromObject(object, jsCfg).toString();
	}

	public String covtObjectToJson(Object object, String[] ignoreField)
	{
		JsonConfigDate jsCfg = new JsonConfigDate(ignoreField);
		return JSONObject.fromObject(object, jsCfg).toString();
	}

	

	public String getCallback()
	{
		return callback;
	}

	public void setCallback(String callback)
	{
		this.callback = callback;
	}

	
}
